import { defaultArchFromString } from 'builder-util'
import { Arch, build, Configuration, FileSet } from 'electron-builder'
import { normalizePath } from 'vite'
import { UserOptions } from './options'
import { packageJson, toArray } from './utils'

export const buildElectron = async (options: UserOptions, root: string, outputDir: string) => {
  const archOpts = process.argv
    .filter(v => v.startsWith('--'))
    .map(v => {
      try {
        return defaultArchFromString(v.substring(2))
      } catch {}
    })
    .filter(Boolean) ?? [defaultArchFromString()]

  let packageBuild: Configuration | undefined = packageJson?.build

  const directories = {
    output: packageBuild?.directories?.output || options.build?.directories?.output || 'build',
    app: packageBuild?.directories?.app || options.build?.directories?.app,
    buildResources: packageBuild?.directories?.buildResources || options.build?.directories?.buildResources
  }

  await build({
    x64: archOpts.includes(Arch.x64),
    ia32: archOpts.includes(Arch.ia32),
    armv7l: archOpts.includes(Arch.armv7l),
    arm64: archOpts.includes(Arch.arm64),
    universal: archOpts.includes(Arch.universal),
    dir: process.argv.includes('--dir'),
    projectDir: root,
    config: {
      asar: false,
      win: { target: 'nsis' },
      ...packageBuild,
      ...options.build,
      files: [
        {
          from: normalizePath(outputDir),
          to: '.'
        },
        'package.json',
        '!**/node_modules/*/{test,__tests__,tests,powered-test,example,examples}',
        '!**/{.DS_Store,.git,.hg,.svn,CVS,RCS,SCCS,.gitignore,.gitattributes}',
        '!**/{npm-debug.log,yarn.lock,.yarn-integrity,.yarn-metadata.json}',
        '!.editorconfig',
        ...toArray<string | FileSet>(packageBuild?.files).filter(Boolean),
        ...toArray<string | FileSet>(options.build?.files).filter(Boolean)
      ],
      directories
    }
  })
}
